﻿using Mapster;
using SDK.yop.client;
using SDK.yop.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Shop.Core.YOP
{
    /// <summary>
    /// 易宝支付
    /// </summary>
    public static class YopPay
    {
        /// <summary>
        /// appKey
        /// </summary>
        private static string appKey = "app_10088801655";
        /// <summary>
        /// 商编
        /// </summary>
        private static string parentMerchantNo = "10088801655";
        /// <summary>
        /// 商户
        /// </summary>
        private static string merchantNo = "10089030131";
        /// <summary>
        /// 请求根地址
        /// </summary>
        private static string serverRoot = "https://openapi.yeepay.com/yop-center";
        /// <summary>
        /// 私钥
        /// </summary>
        public static string PrivateKey = "MIIEowIBAAKCAQEAvQ7wtidGIohlissvUwRnCzoiToxrt8/9c9SW6YhX+LjSIueq3uuvumMd9dZhVSREy6l1MClOxju9I2kZrm5mtsbfe+pDobSPiSjZgsBc/vyw6hDkEaq6qbWerZQThcx47hYNWae+/j/qiTeRoS2x0d+eQ4kaKy94KOD95pncdC3vQT8kVeAs3rSyhdj23rR8k32J5Yj/WtvwaJlqw1VRi2N2tiGdfnT8YYIMJYSlP/QPkeugetKxE7B1BcE9s63e1CTMS3ORS0z9P0A8qcXBfMSDhBLUT6S+S1Hz0Xseryf2Wk6x4npLuuWC3QC/LVWArh0vOD7bQNf8XgM/D/xNiQIDAQABAoIBAAQke6nCGotPKcpswVC0W/2m/HF0KjgQ2qDbG6NqVWMhyZjyMpBH4cXXviRQ2jkfXlKIGAVCInO9g1tvRhzIVn/Sw7rXWzwD1NFQj9OJm4AK0WWPkS/B6e0mCaAMCpF39X5iBVDdmBXCGMWA7jP16FuM5s7cBjLEC4H5zBZtcKMrBMm7L86cujZzy0eEYjDqeK84Lm3ylhEdeAlyzD6X/pEVIsv4cWmfBodj/bAYUygqx4m836qkRqCC27MJkL2obUEQZJog18jvbRK5c0wXjrGenFMxX2NNaVKHewoqoztNUja9SaCUZttNklmPsFm0bkzqGY3jWfO1c1VeMrUV0nECgYEA95FMrDec1rS4RJQRpuv33FC+PEnRRY01MYEiDfDdPdYle8N9GyJqolRZVh+KWz7EK1yv2xFXd6i0gGCXdAf0u3xMYK/mGE7nVsZvvEcV9QrUII6Ee93UPR/UB9G0SCRlGhyJclw2dxlpFwrQZzc74/7EWje0iW+yIA2X/2r5ccMCgYEAw392HfKrTQpAk9xyJltxd1AkRKvwDrbqSLlSsW6X9ZDtbCHXmvMjSIGoKYdmz/psjotxtzyRGp1ZVUmpeIRLhA7Q/g4aUuADmUC+UFVXl3dpQ/mILkB3+EROk/7DvIZiUpqPs2zx7O214w/dSLzp1X4SgkkdPrsmCAX7/ir6YsMCgYEAsl0D4ZwbqnD/xaDsatfdduTRenwwgyyuY2FHGMYtj+ymitmYXCFatGOTDcKhmwXIrfkUVf/ThcmNamStGZLV1vJB0PNKEr9eWx2SyRJqFmbb2Cz19Iwo6nTw/UUv3z4hfUOMH1GiiAJNvaUz6vlXc/dMnjc+IjrQGdnRZds7pqMCgYBNY2yHiGOFOLS9k3tgcbxl5cSlpoZ93Ky7oxj4AfaHkBpcPr1RqkPiVOkTn3T0iYZlmw+l4IT0Syts1p8OhRg7q33RxBVpjyH9jaKIvG/TFsMF1IazAHQ9RBTzAtvLCktrtaGC/nJ6PtNMkiAfxiCukZyUFItOJNl2PaA2Sh8Z7wKBgHA1yJnj5xdO1AkiN/nhU2msFNWFWT3A+f7LbgLRd4DQ5R3u2OQVebzjHCaygFfxaO+arSj9NFUG1POIPIM0YL/vp1J81S3z79+Ff/Q+m2Fp03WMkTp4+CKauRFuUVZWd7X4H7N2hDJotnqoomlr3Ul/XvqC0+akArSPhTSy2L8/";

        /// <summary>
        /// YOP公钥
        /// </summary>
        public static string YOPPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6p0XWjscY+gsyqKRhw9MeLsEmhFdBRhT2emOck/F1Omw38ZWhJxh9kDfs5HzFJMrVozgU+SJFDONxs8UB0wMILKRmqfLcfClG9MyCNuJkkfm0HFQv1hRGdOvZPXj3Bckuwa7FrEXBRYUhK7vJ40afumspthmse6bs6mZxNn/mALZ2X07uznOrrc2rk41Y2HftduxZw6T4EmtWuN2x4CZ8gwSyPAW5ZzZJLQ6tZDojBK4GZTAGhnn3bg5bBsBlw2+FLkCQBuDsJVsFPiGh/b6K/+zGTvWyUcu+LUj2MejYQELDO3i2vQXVDk7lVi2/TcUYefvIcssnzsfCfjaorxsuwIDAQAB";
        
        /// <summary>
        /// 统一支付
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <param name="orderAmount"></param>
        /// <returns></returns>
        public static PrePayReturnDto? Pay(string orderId,string userId, decimal orderAmount,string notifyUrl)
        {
            string apiUri = "/rest/v1.0/aggpay/pre-pay";

            YopRequest request = new YopRequest(appKey, PrivateKey, "https://openapi.yeepay.com/yop-center", YOPPublicKey);
            request.addParam("parentMerchantNo", parentMerchantNo);//非必填
            request.addParam("merchantNo", merchantNo);//非必填
            request.addParam("orderId", orderId);//非必填
            request.addParam("orderAmount", orderAmount.ToString());//非必填
            //request.addParam("expiredTime", "2023-2-20 20:00:00");//非必填
            request.addParam("notifyUrl", notifyUrl);//非必填
            //request.addParam("redirectUrl", "https://notify.merchant.com/xxx");//非必填
            //request.addParam("memo", "测试单");//非必填
            request.addParam("goodsName", "商品");
            request.addParam("fundProcessType", "REAL_TIME");//非必填
            request.addParam("payWay", "MINI_PROGRAM");//必填
            request.addParam("channel", "WECHAT");//必填
            request.addParam("scene", "OFFLINE");//非必填
            request.addParam("appId", "wxddc8918ab2efd5fd");//非必填
            request.addParam("userId", userId);//非必填
            request.addParam("userIp", "123.123.123.123");//必填
            try
            {
                YopResponse response = YopRsaClient.postRsa(apiUri, request);
                if (response.isSuccess())
                {
                    var result = System.Text.Json.JsonSerializer.Deserialize<ResultDto<PrePayReturnDto>>(response.result.ToString());
                    return result.result;
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine("调用失败:" + e);
                return null;
            }
        }

        /// <summary>
        /// 银行卡识别
        /// </summary>
        /// <param name="bankCardNo"></param>
        /// <returns></returns>
        public static BankCardDto BankCardIdentification(string bankCardNo)
        {
            YopRequest request = new(appKey, PrivateKey, serverRoot, YOPPublicKey);

            request.addParam("bankCardNo", bankCardNo);
            string apiUri = "/rest/v1.0/frontcashier/getcardbin";
            YopResponse response = YopRsaClient.postRsa(apiUri, request);
            if (response.isSuccess())
            {
                var data = JsonSerializer.Deserialize<ResultDto<BankCardDto>>(response.result.ToString());
                return data.result;
            }
            else
                return null;
        }

        /// <summary>
        /// 打款
        /// </summary>
        /// <param name="requestId">请求Id</param>
        /// <param name="Amount">金额</param>
        /// <param name="AccountNo">账号ID</param>
        /// <param name="AccountName">账号名称</param>
        /// <param name="AccountCode">账号Code</param>
        /// <param name="AccountCode">通知地址</param>
        /// <returns></returns>
        public static TransferReturnDto Transfer(string requestId,decimal Amount,string AccountNo,string AccountName, string AccountCode,string notifyUrl)
        {
            YopRequest request = new(appKey, PrivateKey, serverRoot, YOPPublicKey);       
            request.addParam("parentMerchantNo", parentMerchantNo);//业务发起方商编
            request.addParam("merchantNo", merchantNo);//商户编号
            request.addParam("requestNo", requestId);//商户请求号
            request.addParam("orderAmount", Amount.ToString());//付款金额
            request.addParam("feeChargeSide", "PAYER");//手续费承担方  PAYER:付款方; PAYEE:收款方
            request.addParam("receiveType", "TWO_HOUR");//到账类型  REAL_TIME:实时;TWO_HOUR:两小时到账;NEXT_DAY:次日到账
            request.addParam("receiverAccountNo", AccountNo);//收款方银行账号
            request.addParam("receiverAccountName", AccountName);//收款方开户名
            request.addParam("receiverBankCode", AccountCode);//收款方开户行银行卡所在开户行编号
            request.addParam("bankAccountType", "DEBIT_CARD");//收款方账户类型
            //request.addParam("branchBankCode", "320903100019");//支行编码
            request.addParam("comments", "提现");//银行附言
            request.addParam("terminalType", "PC");//终端类型
            request.addParam("notifyUrl", notifyUrl);//回调通知地址
            //request.addParam("remark", "测试");//备注
            //request.addParam("receiptComments", "receiptComments_example");//回单备注
            string apiUri = "/rest/v1.0/account/pay/order";

            YopResponse response = YopRsaClient.postRsa(apiUri, request);
            if (response.isSuccess())
            {
                var data = JsonSerializer.Deserialize<ResultDto<TransferReturnDto>>(response.result.ToString());
                return data.result;
            }
               
            return new TransferReturnDto();
        }


        /// <summary>
        /// 易宝通知信息解析
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string NoticeDecrypt(string data)
        {
            return SHA1withRSA.NoticeDecrypt(data, PrivateKey, YOPPublicKey);
        }
    }
}
